cmake_minimum_required(VERSION 3.5)
project(firmware)
find_package(ament_cmake REQUIRED)
find_package(agv_srvs REQUIRED)
find_package(rclcpp REQUIRED)
find_package(rclpy REQUIRED)
find_package(std_msgs REQUIRED)

find_package(Git QUIET)

set(COMMIT_HASH "")
set(BRANCH_NAME "")

find_package(Git QUIET)

###########
## Build ##
###########

include_directories(
  include
  ${Boost_INCLUDE_DIRS}
)

file(GLOB_RECURSE SRCS 
  include/lib/*.cpp
)

add_executable(${PROJECT_NAME} src/firmware.cpp ${SRCS})
ament_target_dependencies(${PROJECT_NAME} "agv_srvs" "std_msgs" "rclcpp")

add_executable(firmwaretest src/firmwaretest.cpp ${SRCS})
ament_target_dependencies(firmwaretest "agv_srvs" "std_msgs" "rclcpp")

install(
  DIRECTORY include/
  DESTINATION include/${PROJECT_NAME}
  FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp"
)

install(TARGETS ${PROJECT_NAME} firmwaretest
  RUNTIME DESTINATION lib/${PROJECT_NAME}
)
install(TARGETS ${PROJECT_NAME} firmwaretest
  ARCHIVE DESTINATION lib
  LIBRARY DESTINATION lib
  RUNTIME DESTINATION bin
)

ament_package()

if(GIT_FOUND)
execute_process(
    COMMAND ${GIT_EXECUTABLE} log -1 --pretty=format:%h
    OUTPUT_VARIABLE COMMIT_HASH
    OUTPUT_STRIP_TRAILING_WHITESPACE
    ERROR_QUIET
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)
execute_process(
    COMMAND ${GIT_EXECUTABLE} symbolic-ref --short -q HEAD
    OUTPUT_VARIABLE BRANCH_NAME
    OUTPUT_STRIP_TRAILING_WHITESPACE
    ERROR_QUIET
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)
execute_process(
    COMMAND ${GIT_EXECUTABLE} describe --abbrev=0 --tags 
    OUTPUT_VARIABLE TAG_NAME
    OUTPUT_STRIP_TRAILING_WHITESPACE
    ERROR_QUIET
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)
endif()
message(STATUS "Git version is ${TAG_NAME}:${BRANCH_NAME}:${COMMIT_HASH}")

if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/include/firmware/ver.h")
    message(STATUS "File ver.h exists.")
    execute_process(
        COMMAND chmod 644 "${CMAKE_CURRENT_SOURCE_DIR}/include/firmware/ver.h"
        RESULT_VARIABLE chmod_result
    )

    if(chmod_result EQUAL 0)
        message(STATUS "Successfully set permissions for ver.h.")
    else()
        message(FATAL_ERROR "Failed to set permissions for ver.h. Error code: ${chmod_result}")
    endif()
else()
    message(STATUS "File ver.h does not exist, create it later.")
endif()

configure_file(
  ${CMAKE_CURRENT_SOURCE_DIR}/ver.h.ini
  ${CMAKE_CURRENT_SOURCE_DIR}/include/firmware/ver.h
  @ONLY
)




